﻿using System;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Xml;

namespace TrainTicketsRobot
{
    internal class WebBot
    {
        private static HttpWebRequest request;

        public static string ReadStream(HttpWebResponse respRtn)
        {
            StreamReader reader;
            Stream responseStream = respRtn.GetResponseStream();
            if (respRtn.Headers["Content-Encoding"] == "gzip")
            {
                GZipStream stream = new GZipStream(responseStream, CompressionMode.Decompress);
                reader = new StreamReader(stream, Encoding.UTF8);
            }
            else
            {
                reader = new StreamReader(responseStream, Encoding.UTF8);
            }
            string str = reader.ReadToEnd();
            reader.Close();
            responseStream.Close();
            respRtn.Close();
            request.KeepAlive = false;
            return str;
        }

        private static bool RemoteCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }

        public static HttpWebResponse SendData(Uri uri, ref CookieContainer cookconReq)
        {
            return SendData(uri, "", ref cookconReq, false);
        }

        public static HttpWebResponse SendData(Uri uri, ref CookieContainer cookconReq, bool IsAjax)
        {
            return SendData(uri, "", ref cookconReq, IsAjax);
        }

        public static HttpWebResponse SendData(Uri uri, string strPostData, ref CookieContainer cookconReq)
        {
            return SendData(uri, strPostData, ref cookconReq, false);
        }

        public static HttpWebResponse SendPostData(Uri uri, string strPostData, ref CookieContainer cookconReq)
        {
            return SendPostData(uri, strPostData, ref cookconReq, false);
        }

        public static HttpWebResponse SendData(Uri uri, string strPostData, ref CookieContainer cookconReq, bool IsAjax)
        {
            HttpWebResponse response2;
            try
            {
                ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(WebBot.RemoteCertificateValidationCallback);
                request = (HttpWebRequest) WebRequest.Create(uri);
                request.AllowAutoRedirect = true;
                if (cookconReq.Count == 0)
                {
                    request.CookieContainer = new CookieContainer();
                    cookconReq = request.CookieContainer;
                }
                else
                {
                    request.CookieContainer = cookconReq;
                }
                if (IsAjax)
                {
                    request.Headers["x-requested-with"] = "XMLHttpRequest";
                }
                request.Accept = "image/jpeg, application/x-ms-application, image/gif, application/xaml+xml, image/pjpeg, application/x-ms-xbap, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";
                if (IsAjax)
                {
                    request.Accept = "text/plain, */*";
                    request.ContentType = "application/x-www-form-urlencoded";
                    request.Referer = "https://dynamic.12306.cn/otsweb/order/querySingleAction.do?method=init";
                }
                request.Headers["Accept-Language"] = "zh-CN";
                request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)";
                request.Host = "dynamic.12306.cn";
                if (IsAjax)
                {
                    request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; EmbeddedWB 14.52 from: http://www.bsalsa.com/ EmbeddedWB 14.52; ";
                }
                request.Headers["Accept-Encoding"] = "gzip, deflate";
                request.KeepAlive = true;
                if (strPostData.Equals(""))
                {
                    request.Method = "GET";
                }
                else
                {
                    request.Method = "POST";
                    request.ContentType = "application/x-www-form-urlencoded";
                    request.Referer = "https://dynamic.12306.cn/otsweb/order/confirmPassengerAction.do?method=init";
                    request.Headers["Cache-Control"] = "no-cache";
                    request.ServicePoint.Expect100Continue = false;
                    byte[] bytes = Encoding.ASCII.GetBytes(strPostData);
                    request.ContentLength = bytes.Length;
                    string Headers = request.Headers.ToString();
                    
                    using (request.GetRequestStream())
                    {
                        Stream requestStream = request.GetRequestStream();
                        requestStream.Write(bytes, 0, bytes.Length);
                        requestStream.Close();
                    }
                }
                HttpWebResponse response = (HttpWebResponse) request.GetResponse();
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    Exception exception = new Exception();
                    exception.Data.Add("StatusCode", HttpStatusCode.OK);
                    throw exception;
                }
                response2 = response;
            }
            catch (WebException exception2)
            {
                Exception exception3 = new Exception(exception2.Message);
                throw exception3;
            }
            catch (Exception exception4)
            {
                throw exception4;
            }
            return response2;
        }

        public static HttpWebResponse SendPostData(Uri uri, string strPostData, ref CookieContainer cookconReq, bool IsAjax)
        {
            HttpWebResponse response2;
            try
            {
                ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(WebBot.RemoteCertificateValidationCallback);
                request = (HttpWebRequest)WebRequest.Create(uri);
                if (cookconReq.Count == 0)
                {
                    request.CookieContainer = new CookieContainer();
                    cookconReq = request.CookieContainer;
                }
                else
                {
                    request.CookieContainer = cookconReq;
                }
                if (IsAjax)
                {
                    request.Headers["x-requested-with"] = "XMLHttpRequest";
                }
                request.Accept = "image/jpeg, application/x-ms-application, image/gif, application/xaml+xml, image/pjpeg, application/x-ms-xbap, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";
                if (IsAjax)
                {
                    request.Accept = "text/plain, */*";
                    request.ContentType = "application/x-www-form-urlencoded";
                    request.Referer = "https://dynamic.12306.cn/otsweb/order/querySingleAction.do?method=init";
                }
                request.Headers["Accept-Language"] = "zh-CN";
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C)";
                if (IsAjax)
                {
                    request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; EmbeddedWB 14.52 from: http://www.bsalsa.com/ EmbeddedWB 14.52; ";
                }
                request.Headers["Accept-Encoding"] = "gzip, deflate";
                request.KeepAlive = true;
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.Referer = "https://dynamic.12306.cn/otsweb/order/confirmPassengerAction.do?method=init";
                request.Headers["Cache-Control"] = "no-cache";
                request.ServicePoint.Expect100Continue = false;
                byte[] bytes = Encoding.ASCII.GetBytes(strPostData);
                request.ContentLength = bytes.Length;
                using (request.GetRequestStream())
                {
                    Stream requestStream = request.GetRequestStream();
                    requestStream.Write(bytes, 0, bytes.Length);
                    requestStream.Close();
                }
                
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    Exception exception = new Exception();
                    exception.Data.Add("StatusCode", HttpStatusCode.OK);
                    throw exception;
                }
                response2 = response;
            }
            catch (WebException exception2)
            {
                Exception exception3 = new Exception(exception2.Message);
                throw exception3;
            }
            catch (Exception exception4)
            {
                throw exception4;
            }
            return response2;
        }

        public static string strProcessError(Exception ex)
        {
            if (ex.Data.Contains("StatusCode"))
            {
                return "网站忙，连接失败！";
            }
            return ex.Message;
        }
    }
}

